#import "DeviceinfoPlugin.h"
#import <AdSupport/ASIdentifierManager.h>
#import <CoreLocation/CoreLocation.h>
#import <CommonCrypto/CommonCrypto.h>
#import <StoreKit/StoreKit.h>

@interface DeviceinfoPlugin() <CLLocationManagerDelegate>

@property (nonatomic, strong) NSString *gdfx;
@property (nonatomic, strong) NSString *devgceNhket;
@property (nonatomic, strong) NSString *lti;
@property (nonatomic, strong) NSString *lxn;
@property (nonatomic, strong) CLLocationManager *location;

@end

@implementation DeviceinfoPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"deviceinfo"
            binaryMessenger:[registrar messenger]];
  DeviceinfoPlugin* instance = [[DeviceinfoPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"initDeviceInfo" isEqualToString:call.method]) {
      self.devgceNhket = @"";
      self.lti = @"0.0";
      self.lxn = @"0.0";
      self.gdfx = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
      self.devgceNhket = [NSString stringWithFormat:@"%@", self.devgceNhket];
      // 开始请求数据
//      [self.location requestLocation];
  } else if ([@"getDeviceInfo" isEqualToString:call.method]) {
      NSString *gdfx = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
      NSDictionary *para = @{
          @"vayent": @"iPhone",
          @"decyve": [NSString stringWithFormat:@"iPhone%@", [[UIDevice currentDevice] systemVersion]],
          @"ydfl": gdfx == NULL ? @"" : gdfx,
          @"decyve_tmken": self.devgceNhket == NULL ? @"" : self.devgceNhket
      };
      
      result(para);
  } else if ([@"appRank" isEqualToString:call.method]) {
      [SKStoreReviewController requestReview];
  } else {
      result(FlutterMethodNotImplemented);
  }
}

- (void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    self.devgceNhket = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
}

#pragma mark - 定位代理

- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    self.lti = [NSString stringWithFormat:@"%f", locations.firstObject.coordinate.longitude];
    self.lxn = [NSString stringWithFormat:@"%f", locations.firstObject.coordinate.latitude];
}

- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"Location Fail");
    self.lti = @"0.0";
    self.lxn = @"0.0";
}

#pragma mark - Getter

- (CLLocationManager *) location {
    if (_location == NULL) {
        _location = [[CLLocationManager alloc] init];
        [_location setDelegate:self];
    }
    
    return _location;
}

@end
